/**
 * 认证相关 API
 */
import axios from 'axios'
import { setToken, getToken } from '../utils/token'

// 创建 axios 实例
const request = axios.create({
  baseURL: '/api', // 根据实际后端地址配置
  timeout: 5000
})

// 请求拦截器:添加 token
request.interceptors.request.use(
  (config) => {
    // 登录接口不需要添加token
    if (!config.url.includes('/login')) {
      const token = getToken()
      if (token) {
        config.headers.JWTtoken = token
      }
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器：处理错误
request.interceptors.response.use(
  (response) => {
    return response
  },
  (error) => {
    if (error.response?.status === 401) {
      // token 过期或无效，清除并跳转到登录页
      localStorage.removeItem('jwt_token')
      window.location.href = '/login'
    }
    return Promise.reject(error)
  }
)

/**
 * 密码登录
 * @param {string} phoneNumber - 手机号
 * @param {string} password - 密码
 * @returns {Promise}
 */
export const loginWithPassword = async (phoneNumber, password) => {
  const response = await request.post('/login', {
    phoneNumber,
    password
  })
  // 后端返回格式: { code: 1, msg: "success", data: "token" }
  if (response.data.code === 1 && response.data.data) {
    setToken(response.data.data)
  }
  return response.data
}

/**
 * 手机号验证码登录
 * @param {string} phone - 手机号
 * @param {string} code - 验证码
 * @returns {Promise}
 */
export const loginWithPhone = async (phone, code) => {
  const response = await request.post('/auth/login/phone', {
    phone,
    code
  })
  if (response.data.token) {
    setToken(response.data.token)
  }
  return response.data
}

/**
 * 发送验证码
 * @param {string} phone - 手机号
 * @returns {Promise}
 */
export const sendVerifyCode = async (phone) => {
  const response = await request.post('/auth/send-code', {
    phone
  })
  return response.data
}

/**
 * 用户注册
 * @param {Object} userData - 用户注册信息
 * @returns {Promise}
 */
export const register = async (userData) => {
  const response = await request.post('/auth/register', userData)
  return response.data
}

/**
 * 退出登录
 * @returns {Promise}
 */
export const logout = async () => {
  const response = await request.post('/auth/logout')
  return response.data
}

/**
 * 创建班级
 * @param {string} className - 班级名称
 * @returns {Promise}
 */
export const createClass = async (className) => {
  const response = await request.post('/Classes', {
    className
  })
  return response.data
}

/**
 * 获取班级列表
 * @returns {Promise}
 */
export const getClassList = async () => {
  const response = await request.get('/Classes')
  return response.data
}

/**
 * 通过学号导入学生
 * @param {string} classId - 班级ID
 * @param {Array<string>} cardIds - 学号列表
 * @returns {Promise}
 */
export const addStudentByCardId = async (classId, cardIds) => {
  const response = await request.post('/AddStudentByCardId', {
    classId,
    cardIds
  })
  return response.data
}
